package com.example.music_project.pages;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.music_project.R;
import com.example.music_project.utils.AuthUtils;

public class LoginActivity extends AppCompatActivity {

    private EditText editAccount, editPassword;
    private CheckBox checkSave;
    private SharedPreferences sharedPreferences;
    public static final String PREFS_NAME = "LoginPrefs";
    private static final String PREF_USERNAME = "username";
    private static final String PREF_PASSWORD = "password";
    private static final String PREF_SAVE = "save";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // 初始化 AuthUtils（数据库或网络认证）
        AuthUtils.init(this);

        // 视图绑定
        editAccount = findViewById(R.id.edit_account);
        editPassword = findViewById(R.id.edit_password);
        checkSave = findViewById(R.id.check_save);
        Button btnLogin = findViewById(R.id.btn_login);
        Button btnRegister = findViewById(R.id.btn_register);

        // 初始化 SharedPreferences
        sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

        // 检查是否记住密码，并自动填充
        if (sharedPreferences.getBoolean(PREF_SAVE, false)) {
            editAccount.setText(sharedPreferences.getString(PREF_USERNAME, ""));
            editPassword.setText(sharedPreferences.getString(PREF_PASSWORD, ""));
            checkSave.setChecked(true);
        }

        // 登录按钮点击事件
        btnLogin.setOnClickListener(v -> handleLogin());

        // 注册按钮点击事件
        btnRegister.setOnClickListener(v ->
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class))
        );
    }

    private void handleLogin() {
        String username = editAccount.getText().toString().trim();
        String password = editPassword.getText().toString().trim();

        // 输入验证
        if (TextUtils.isEmpty(username)) {
            editAccount.setError(getString(R.string.error_username_empty));
            return;
        }
        if (TextUtils.isEmpty(password)) {
            editPassword.setError(getString(R.string.error_password_empty));
            return;
        }

        // 调用 AuthUtils 进行登录验证
        if (AuthUtils.login(this, username, password)) {
            saveLoginCredentialsIfNeeded(username, password);
            startActivity(new Intent(this, MainActivity.class));
            finish();

            // LoginActivity.java（登录成功后保存数据）
            SharedPreferences sharedPreferences = getSharedPreferences("user_data", MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("username", username);
            editor.apply();

        } else {
            Toast.makeText(this, R.string.login_failed, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 仅在用户勾选“记住密码”时保存用户名和密码
     */
    private void saveLoginCredentialsIfNeeded(String username, String password) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if (checkSave.isChecked()) {
            editor.putString(PREF_USERNAME, username);
            editor.putString(PREF_PASSWORD, password);
            editor.putBoolean(PREF_SAVE, true);
        } else {
            // 如果未勾选“记住密码”，清除保存的密码（但保留用户名）
            editor.remove(PREF_PASSWORD);
            editor.putBoolean(PREF_SAVE, false);
        }
        editor.apply();
    }
}